package com.authine.cloudpivot.ext.controller.workList;

import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.Utils.Utils;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


@Slf4j
@RestController
@RequestMapping("/public/SiteProblemController")
public class SiteProblemController extends BaseController {



    @Autowired
    CloudSqlService sqlService;



    /**
     * 场地问题项提出-新增  审批流完成后 数据写到-场地问题项基础表
     */
    @RequestMapping("siteProblemForwardFinsh")
    public void siteProblemForwardFinsh(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.SiteForward, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.SiteForwardDetail);
        String approval = "";
//        String approval = getFileBaseInfoWorkFlowApproval(bizObject,"Activity22");
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        for (Map<String, Object> map : list) {
            try {
//                Map<String, Object> data = Utils.fileInfoBaseMap(map,approval);
                Map<String, Object> data = fileInfoBaseMap01(map, now, approval);
//                 判断是否是修改
                String basicId = existsBizObject(map);
//                String basicId = MapUtils.getString(map, "basicId", "");
                if(StringUtils.isNotBlank(basicId)){
                    //基础信息表id
                    data.put("id",basicId);
                }
                data.put("workContent", map.get("workContent"));//工作说明
//                data.put("manangeDeptNumber", map.get("manageDeptFNumber"));//管理部门代码
//                data.put("manangeDeptNumber", map.get("manageDeptFNumber"));

                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.SiteForwardBasic, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                String id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
//                getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);

                log.info("基础表-人员信息基础更新成功:{}", id);
                // 存储过程
                siteProblemForwardFinishProcess(id);
            } catch (Exception e) {
                log.info("原始表数据:{}", JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }


    private String existsBizObject(Map data) {

//        //事项基础表id映射
//        String eventObjectId = (String) data.get("relevancePlaceCodeId");
        String itemCode = (String) data.get("ShortText1676533437299");//事项代码
        //场地代码关联
        log.info("relevancePlaceCode:{}", data.get("relevancePlaceCode"));

        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.SiteForwardBasic);

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName).append(" where ShortText1676533437299 ='").append(itemCode).append("' ORDER BY createdTime desc limit 1");

        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    @RequestMapping("siteProblemForwardToVoid")
    public void siteProblemForwardToVoid(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.SiteForwardCancel, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.SiteForwardDetailCancel);
        //获取审批人
//        String approval = getFileBaseInfoWorkFlowApproval(bizObject,"Activity22");
        String approval = "";
//        String approval = getFileBaseInfoWorkFlowApproval(bizObject,"Activity22");
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        for (Map<String, Object> map : list) {
            try {

                //获取数据
//                Map<String, Object> data = fileInfoBaseMap01(map, now, approval);
                Map<String, Object> data = Utils.fileInfoBaseMap(map,approval);
                //判断是否已存在
                String id = existsBizObject(data);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.SiteForwardBasic, data, false);
                model.setSequenceStatus(SequenceStatus.CANCELED.name());
                getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                //调用存储过程
                Map<String, Object> company = ( Map<String, Object> )map.get("company");
                 siteProblemForwardToVoidProcess(id);
            } catch (Exception e) {
                log.info("参数：{}",JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }


    /**
     * 场地问题项实施-新增  审批流完成后 数据写到-场地问题项基础表
     */
    @RequestMapping("siteImplementFinsh")
    public void siteImplementFinsh(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.SiteImplement, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.SiteImplementDetail);
        String approval = "";
//        String approval = getFileBaseInfoWorkFlowApproval(bizObject,"Activity22");
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        for (Map<String, Object> map : list) {
            try {
                Map<String, Object> data = fileInfoBaseMap01(map, now, approval);
//                 判断是否是修改
                String basicId = existsBizObject02(map);
//                String basicId = MapUtils.getString(map, "basicId", "");
                if(StringUtils.isNotBlank(basicId)){
                    //基础信息表id
                    data.put("id",basicId);
                }
                data.put("finishDate", map.get("FinishDate"));//完成日期
                data.put("workContent2", map.get("workContent"));//工作说明
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.SiteForwardBasic, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                String id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                // 存储过程
                 siteImplementFinshProcess(id);
            } catch (Exception e) {
                log.info("原始表数据:{}", JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }
    /**
     * ----场地问题项提出
     SiteProblemPlan
     (
     @companynum   nvarchar(50),		-----公司代码
     @SiteCode	  nvarchar(100),	-----场地代码
     @creatorcode	  nvarchar(100),	-----意见人代码
     @creator	  nvarchar(20),		-----意见人，
     @plandate	  nvarchar(50),		-----提出时间  YYYY-MM-DD
     @sitetype	  nvarchar(50),		-----事项类别
     @Number		  nvarchar(100),	-----事项代码
     @Name		  nvarchar(200),	-----事项
     @MaindeptCode	 nvarchar(50),	-----责任部门代码
     @EmpCode		nvarchar(50),	-----责任人代码
     @ExpDate		nvarchar(50),	-----计划完成时间
     @workdesc		nvarchar(100),	-----工作说明
     @Auditor		nvarchar(50)	----审批人 02.0100 张三
     )
     */
    private void siteProblemForwardFinishProcess(String bizId) {

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.SiteForwardBasic);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("场地信息记录-callProcess-入参map={}", JSONObject.toJSONString(map));

        //调用存储过程
        String companyCode = MapUtils.getString(map, "companyCode", "");
        String siteNumber = MapUtils.getString(map, "siteNumber", "");
        String advicerNumber = MapUtils.getString(map, "advicerNumber", "");
        String advicerName = MapUtils.getString(map, "advicerName", "");

        LocalDateTime tichuDateTemp = (LocalDateTime) map.get("Date1676532795601");
        String tichuDate =  ObjectUtils.isEmpty(tichuDateTemp) ? "" : tichuDateTemp.toLocalDate().toString();

        String itemType = MapUtils.getString(map, "Dropdown1676533345786", "");
        String itemNumber = MapUtils.getString(map, "ShortText1676533437299", "");
        String itemName = MapUtils.getString(map, "ShortText1676533439713", "");

        String responsDeptNumber = MapUtils.getString(map, "responsDeptNumber", "");//
        String responsiblePersonNumber = MapUtils.getString(map, "responsiblePersonNumber", "");

//                String expiryDateString = ObjectUtils.isEmpty(complateTime) ? "is null" : "= '"+complateTime.toString()+"'";
//        expiryDateString= ObjectUtils.isEmpty(expiryDate) ?"is null" : "= '"+expiryDateString.substring(3,22)+"'";
        LocalDateTime complateTimeTemp = (LocalDateTime) map.get("complateTime");
        String complateTime =  ObjectUtils.isEmpty(complateTimeTemp) ? "" : complateTimeTemp.toLocalDate().toString();

        String workContent = MapUtils.getString(map, "workContent", "");
        String approval = MapUtils.getString(map, "approval", "");//审批人   02.0100 张三

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SiteProblemPlan '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                companyCode, siteNumber, advicerNumber, advicerName,tichuDate, itemType, itemNumber, itemName, responsDeptNumber, responsiblePersonNumber, complateTime, workContent, approval);
        log.info("\n==========准备调用[场地信息记录]存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[场地信息记录]存储过程执行完成");
    }

    /**
     * ----场地问题提出 作废
     exec   proc    SiteProblemVoid
     (
     @number			nvarchar(50)	----事项代码
     )
     */
    private void siteProblemForwardToVoidProcess(String bizId) {

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.placeInformationBase);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());
        log.info("入参map={}", map);

        //准备调用存储过程的入参
        String itemNumber = MapUtils.getString(map, "ShortText1676533437299", "");//事项代码

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SiteProblemVoid '%s'", itemNumber);
        log.info("\n==========准备调用[场地信息记录   作废]存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[场地信息记录   作废]存储过程执行完成");

    }



    /**
     * ----场地问题项实施
     * exec    SiteProblemFinish
     * (
     *        @number			nvarchar(50),	----事项代码    * 	@CompleteDate nvarchar(50),        ----完成时间
     *        @workdesc		nvarchar(100)	-----工作说明
     * )
     */
    private void siteImplementFinshProcess(String bizId) {

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.placeInformationBase);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());
        log.info("入参map={}", map);

        //准备调用存储过程的入参
        String itemNumber = MapUtils.getString(map, "ShortText1676533437299", "");//事项代码
        String workContent = MapUtils.getString(map, "workContent2", "");
        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SiteProblemFinish '%s','%s'", itemNumber,workContent);
        log.info("\n==========准备调用[场地信息记录   作废]存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[场地信息记录   作废]存储过程执行完成");

    }

    private String existsBizObject02(Map data) {

//        //事项基础表id映射
//        String eventObjectId = (String) data.get("relevancePlaceCodeId");
        String itemCode = (String) data.get("ShortText1676533437299");//事项代码
        //场地代码关联
        log.info("relevancePlaceCode:{}", data.get("relevancePlaceCode"));

        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.SiteForwardBasic);

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName).append(" where ShortText1676533437299 ='").append(itemCode).append("' ORDER BY createdTime desc limit 1");

        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    @RequestMapping("siteImplementToVoid")
    public void siteImplementToVoid(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.SiteImplementCancel, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.SiteImplementDetailCancel);
        String approval = "";
//        String approval = getFileBaseInfoWorkFlowApproval(bizObject,"Activity22");
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        for (Map<String, Object> map : list) {
            try {
                //获取数据
                Map<String, Object> data = fileInfoBaseMap01(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(data);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.SiteForwardBasic, data, false);
                model.setSequenceStatus(SequenceStatus.CANCELED.name());
                getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                //调用存储过程
                Map<String, Object> company = ( Map<String, Object> )map.get("company");
                //  siteImplementToVoidProcess(company.get("id").toString(),MapUtils.getString(map, "eventCode", ""));
            } catch (Exception e) {
                log.info("参数：{}",JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }


    /**
     * 命名记录  审批流完成后 数据写到-命名记录基础表
     */
    @RequestMapping("siteItemFinsh")
    public void siteItemFinsh(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.SiteItem, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.SiteItemDetail);
        String approval = getFileBaseInfoWorkFlowApproval(bizObject,"Activity22");
        for (Map<String, Object> map : list) {
            try {
                Map<String, Object> data = Utils.fileInfoBaseMap(map,approval);
                // 判断是否是修改
                String basicId = MapUtils.getString(map, "basicId", "");
                if(StringUtils.isNotBlank(basicId)){
                    //基础信息表id
                    data.put("id",basicId);
                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.SiteItemBasic, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                // 存储过程
                // siteItemFinshProcess(data);
            } catch (Exception e) {
                log.info("原始表数据:{}", JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }




    @RequestMapping("siteItemToVoid")
    public void siteItemToVoid(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.SiteItemCancel, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.SiteItemDetailCancel);
        //获取审批人
        String approval = getFileBaseInfoWorkFlowApproval(bizObject,"Activity22");
        for (Map<String, Object> map : list) {
            try {
                String basicId = MapUtils.getString(map, "basicId", "");
                if(StringUtils.isBlank(basicId)){
                    continue;
                }
                //获取数据
                Map<String, Object> data = Utils.fileInfoBaseMap(map,approval);
                data.put("id",basicId);
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.SiteItemBasic, data, false);
                model.setSequenceStatus(SequenceStatus.CANCELED.name());
                getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                //调用存储过程
                Map<String, Object> company = ( Map<String, Object> )map.get("company");
                //  siteItemToVoidProcess(company.get("id").toString(),MapUtils.getString(map, "eventCode", ""));
            } catch (Exception e) {
                log.info("参数：{}",JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }



    /**
     * 查询审批人,返回  员工号+姓名
     *
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject,String finalActivityCode) {
        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }
        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }
        UserModel user = getOrganizationFacade().getUser(participant);
        return new StringBuilder(user.getEmployeeNo()).append("　").append(user.getName()).toString();
    }

    /**
     * 转换成  待完成工作清单 基础表 的数据
     *
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String, Object> fileInfoBaseMap01(Map<String, Object> map, String auditDate, String approval) {
        Map<String, Object> data = new HashMap<>();

        data.put("manangeDeptNumber", map.get("manageDeptFNumber"));//管理部门代码
        data.put("ShortText1676533437299", map.get("ShortText1676533437299"));//事项代码
        data.put("posANumber", map.get("postACode"));//岗A代码
        data.put("responsiblePersonNumber", map.get("responsPersonCode"));//责任人代码
        data.put("company", map.get("company"));//公司
//
        data.put("companyCode", map.get("companyNumber"));//公司代码
//
        data.put("companyName", map.get("companyName"));//公司名称
        data.put("siteCode", map.get("siteCode"));//场地代码
        data.put("siteNumber", map.get("siteNumber"));//场地代码

        data.put("site", map.get("site"));//场地
        data.put("managerText", map.get("managerText"));//管理员
//
        data.put("manangeDeptFid", map.get("manangeDeptFid"));//管理部门代码
        data.put("manangeDeptNumber", map.get("manageDeptFNumber"));//管理部门代码
        data.put("Dept", map.get("Dept"));//管理部门
//
        data.put("ACode", map.get("ACode"));
        data.put("posANumber", map.get("postACode"));
        data.put("postA", map.get("postA"));
        data.put("BCode", map.get("BCode"));
        data.put("posBNumber", map.get("postBCode"));
        data.put("postB", map.get("postB"));

        data.put("advicerNumber", map.get("advicerNumber"));//意见人代码
        data.put("advicerName", map.get("advicerName"));//意见人
//
        data.put("Date1676532795601", map.get("Date1676532795601"));//提出日期
        data.put("Dropdown1676533345786", map.get("Dropdown1676533345786"));//事项类别
        data.put("ShortText1676533439713", map.get("ShortText1676533439713"));//事项

        data.put("responsDeptCode", map.get("responsDeptCode"));//责任部门代码
        data.put("responsDeptNumber", map.get("responsibleDeptFNumber"));//责任部门代码
        data.put("responsDept", map.get("responsDept"));//责任部门
        data.put("responsiblePerson", map.get("responsiblePerson"));//责任人代码
        data.put("responsiblePersonNumber", map.get("responsPersonCode"));//责任人代码
        data.put("responsPerson", map.get("responsPerson"));//责任人

        data.put("complateTime", map.get("complateTime"));//计划完成日期
//        data.put("finishDate", map.get("finishDate"));//完成日期
        //审批时间
        data.put("auditDate", auditDate);
        //审批人
        data.put("approval", approval);
        return data;
    }

}